#include "audio.h"
#include <QSound>
#include <QDebug>


int Audio::play(const char *pathname,int nSampleRate,int nChannels,int fmt)

{

    int dsp_fd,status,arg;

    dsp_fd = ::open("/dev/dsp" , O_RDWR);   /*open dsp*/

    if(dsp_fd < 0)

    {

        return  OPEN_DSP_FAILED;

    }

    arg = nSampleRate;

    status = ::ioctl(dsp_fd,SOUND_PCM_WRITE_RATE,&arg); /*set samplerate*/

    if(status < 0)

    {

        ::close(dsp_fd);

        return SAMPLERATE_STATUS;

    }

    if(arg != nSampleRate)

    {

        ::close(dsp_fd);

        return SET_SAMPLERATE_FAILED;

    }

    arg = nChannels;  /*set channels*/

    status = ::ioctl(dsp_fd, SOUND_PCM_WRITE_CHANNELS, &arg);

    if(status < 0)

    {

        ::close(dsp_fd);

        return CHANNELS_STATUS;

    }

    if( arg != nChannels)

    {

        ::close(dsp_fd);

        return SET_CHANNELS_FAILED;

    }

    arg = fmt; /*set bit fmt*/

    status = ::ioctl(dsp_fd, SOUND_PCM_WRITE_BITS, &arg);

    if(status < 0)

    {

        ::close(dsp_fd);

        return FMT_STATUS;

    }

    if(arg != fmt)

    {

        ::close(dsp_fd);

        return SET_FMT_FAILED;

    }//end of  para end

    ::FILE *file_fd = ::fopen(pathname,"r");

    if(file_fd == NULL)
    {
        ::close(dsp_fd);

        return OPEN_FILE_FAILED;

    }

    int num = 3*nChannels*nSampleRate*fmt/8;

//    int get_num;

    char buf[num];

    //char  headlong;
    ::fseek(file_fd,48,SEEK_SET);
    //fread(&headlong,1,1,file_fd);
    //fseek(file_fd,headlong+16,SEEK_SET);
    while(::feof(file_fd) == 0)
    {

        int get_num = ::fread(buf,1,num,file_fd);
        ::write(dsp_fd,buf,get_num);
        if(get_num != num)

        {
            ::close(dsp_fd);
            ::fclose(file_fd);
            return 0;

        }

    }

    ::close(dsp_fd);
    ::fclose(file_fd);
    return 0;

}

/**
 * @brief Audio::playError
 */
void Audio::playError()
{
    QSound::play(":/sound/error.wav");
}
void Audio::playKeyOrTouch()
{
    QSound::play(":/sound/sound/key&Touch.wav");
}
